import axios from 'axios'
import store from '@/store'
import router from '@/router'

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASEURL
})

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    const token = store.state.User.token
    if (token) config.headers.token = token
    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (error.response.status === 401) {
      // 清除token
      store.commit('User/setToken', '')
      console.log(router.currentRoute.fullPath)
      // 跳转到登陆页面
      router.replace(`/login?redirect=${router.currentRoute.fullPath}`)
    }
    return Promise.resolve({ res: {} })
  }
)

export default instance
